<?php
namespace app\admin\service;

use think\facade\Db;
use think\Config;

class DatabaseService
{
    // 初始化数据库表
    public static function initTables()
    {
        try {
            // 检查并创建管理员表
            self::createAdminTable();
            
            // 检查并创建停车场信息表
            self::createParkInfoTable();
            
            // 检查并创建车位表
            self::createParkingSpacesTable();
            
            // 检查并创建通道表
            self::createChannelsTable();
            
            // 检查并创建车辆表
            self::createVehiclesTable();
            
            // 检查并创建缴费记录表
            self::createPaymentRecordsTable();
            
            // 检查并创建黑名单表
            self::createBlacklistTable();
            
            // 检查并创建设备表
            self::createEquipmentTable();
            
            // 检查并创建维护记录表
            self::createMaintenanceRecordsTable();
            
            // 检查并创建进出场记录表
            self::createParkingRecordsTable();
            
            // 检查并创建续费记录表
            self::createRenewalRecordsTable();
            
            // 检查并创建API调用日志表
            self::createApiLogsTable();
            
            // 检查并创建操作日志表
            self::createOperationLogsTable();
            
            // 更新通道表结构
            self::updateChannelsTable();
            
            // 更新设备表结构
            self::updateEquipmentTable();
            
            // 插入示例数据
            self::insertSampleData();
            
            return ['success' => true, 'message' => '数据库初始化成功'];
        } catch (\Exception $e) {
            return ['success' => false, 'message' => '初始化失败: ' . $e->getMessage()];
        }
    }
    
    // 创建管理员表
    private static function createAdminTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `admins` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `username` varchar(50) NOT NULL COMMENT '用户名',
            `password` varchar(255) NOT NULL COMMENT '密码',
            `real_name` varchar(50) DEFAULT NULL COMMENT '真实姓名',
            `phone` varchar(20) DEFAULT NULL COMMENT '手机号',
            `email` varchar(100) DEFAULT NULL COMMENT '邮箱',
            `status` tinyint(1) DEFAULT 1 COMMENT '状态：1-启用，2-禁用',
            `last_login_time` datetime DEFAULT NULL COMMENT '最后登录时间',
            `last_login_ip` varchar(45) DEFAULT NULL COMMENT '最后登录IP',
            `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `username` (`username`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='管理员表';
        ";
        
        Db::execute($sql);
        
        // 插入默认管理员账号
        $admin = Db::table('admins')->where('username', 'admin')->find();
        if (!$admin) {
            Db::table('admins')->insert([
                'username' => 'admin',
                'password' => password_hash('admin123', PASSWORD_DEFAULT),
                'real_name' => '系统管理员',
                'phone' => '13800138000',
                'email' => 'admin@park.com',
                'status' => 1,
                'create_time' => date('Y-m-d H:i:s')
            ]);
        }
    }
    
    // 创建停车场信息表
    private static function createParkInfoTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `park_info` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `park_name` varchar(100) NOT NULL COMMENT '停车场名称',
            `address` varchar(255) DEFAULT NULL COMMENT '地址',
            `contact_phone` varchar(20) DEFAULT NULL COMMENT '联系电话',
            `total_spaces` int(11) DEFAULT 0 COMMENT '总车位数',
            `used_spaces` int(11) DEFAULT 0 COMMENT '已使用车位数',
            `temp_price_per_hour` decimal(10,2) DEFAULT 5.00 COMMENT '临时停车每小时价格',
            `monthly_price` decimal(10,2) DEFAULT 300.00 COMMENT '月租价格',
            `business_hours` varchar(50) DEFAULT '00:00-23:59' COMMENT '营业时间',
            `description` text COMMENT '描述',
            `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='停车场信息表';
        ";
        
        Db::execute($sql);
        
        // 插入默认停车场信息
        $park = Db::table('park_info')->find();
        if (!$park) {
            Db::table('park_info')->insert([
                'park_name' => '大头停车管理系统',
                'address' => '深圳市南山区科技园',
                'contact_phone' => '0755-12345678',
                'total_spaces' => 500,
                'used_spaces' => 172,
                'temp_price_per_hour' => 5.00,
                'monthly_price' => 300.00,
                'business_hours' => '00:00-23:59',
                'description' => '现代化智能停车场管理系统',
                'create_time' => date('Y-m-d H:i:s')
            ]);
        }
    }
    
    // 创建车位表
    private static function createParkingSpacesTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `parking_spaces` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `space_no` varchar(20) NOT NULL COMMENT '车位号',
            `space_type` tinyint(1) DEFAULT 1 COMMENT '车位类型：1-普通，2-VIP，3-充电桩',
            `status` tinyint(1) DEFAULT 1 COMMENT '状态：1-空闲，2-占用，3-预约，4-维护',
            `vehicle_plate` varchar(20) DEFAULT NULL COMMENT '车牌号',
            `entry_time` datetime DEFAULT NULL COMMENT '入场时间',
            `floor` varchar(10) DEFAULT 'B1' COMMENT '楼层',
            `area` varchar(10) DEFAULT 'A' COMMENT '区域',
            `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `space_no` (`space_no`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='车位表';
        ";
        
        Db::execute($sql);
    }
    
    // 创建通道表
    private static function createChannelsTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `channels` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `channel_name` varchar(50) NOT NULL COMMENT '通道名称',
            `channel_type` tinyint(1) NOT NULL COMMENT '通道类型：1-入口，2-出口',
            `camera_ip` varchar(45) DEFAULT NULL COMMENT '相机IP',
            `status` tinyint(1) DEFAULT 1 COMMENT '状态：1-正常，2-故障，3-维护',
            `location` varchar(100) DEFAULT NULL COMMENT '位置',
            `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='通道表';
        ";
        
        Db::execute($sql);
    }
    
    // 创建车辆表
    private static function createVehiclesTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `vehicles` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `plate_number` varchar(20) NOT NULL COMMENT '车牌号',
            `car_type` tinyint(1) NOT NULL COMMENT '车辆类型：1-临时车，2-月租车，3-储值车',
            `owner_name` varchar(50) DEFAULT NULL COMMENT '车主姓名',
            `phone` varchar(20) DEFAULT NULL COMMENT '联系电话',
            `space_number` varchar(20) DEFAULT NULL COMMENT '分配车位号',
            `expire_date` datetime DEFAULT NULL COMMENT '到期时间',
            `balance` decimal(10,2) DEFAULT 0.00 COMMENT '余额（储值车用）',
            `status` tinyint(1) DEFAULT 1 COMMENT '状态：1-正常，2-过期，3-锁定，4-禁用',
            `entry_time` datetime DEFAULT NULL COMMENT '入场时间',
            `remark` text COMMENT '备注',
            `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            KEY `plate_number` (`plate_number`),
            KEY `car_type` (`car_type`),
            KEY `status` (`status`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='车辆表';
        ";
        
        Db::execute($sql);
    }
    
    // 创建缴费记录表
    private static function createPaymentRecordsTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `payment_records` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `order_no` varchar(32) NOT NULL COMMENT '订单号',
            `plate_number` varchar(20) NOT NULL COMMENT '车牌号',
            `entry_time` datetime NOT NULL COMMENT '入场时间',
            `exit_time` datetime DEFAULT NULL COMMENT '出场时间',
            `parking_duration` int(11) DEFAULT 0 COMMENT '停车时长（分钟）',
            `total_fee` decimal(10,2) DEFAULT 0.00 COMMENT '总费用',
            `discount_amount` decimal(10,2) DEFAULT 0.00 COMMENT '优惠金额',
            `actual_fee` decimal(10,2) DEFAULT 0.00 COMMENT '实际支付费用',
            `payment_method` varchar(20) DEFAULT NULL COMMENT '支付方式',
            `payment_status` varchar(20) DEFAULT 'unpaid' COMMENT '支付状态：paid-已支付，unpaid-未支付',
            `pay_time` datetime DEFAULT NULL COMMENT '支付时间',
            `channel_id` int(11) DEFAULT NULL COMMENT '通道ID',
            `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `order_no` (`order_no`),
            KEY `plate_number` (`plate_number`),
            KEY `payment_status` (`payment_status`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='缴费记录表';
        ";
        
        Db::execute($sql);
    }
    
    // 创建黑名单表
    private static function createBlacklistTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `blacklist` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `plate_number` varchar(20) NOT NULL COMMENT '车牌号',
            `type` tinyint(1) NOT NULL COMMENT '类型：1-永久黑名单，2-临时黑名单，3-恶意逃费',
            `reason` varchar(255) DEFAULT NULL COMMENT '加入黑名单原因',
            `start_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '开始时间',
            `end_time` datetime DEFAULT NULL COMMENT '结束时间（永久黑名单为NULL）',
            `status` tinyint(1) DEFAULT 1 COMMENT '状态：1-启用，2-禁用',
            `operator` varchar(50) DEFAULT NULL COMMENT '操作员',
            `remark` text COMMENT '备注',
            `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            KEY `plate_number` (`plate_number`),
            KEY `type` (`type`),
            KEY `status` (`status`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='黑名单表';
        ";
        
        Db::execute($sql);
    }
    
    // 创建设备表
    private static function createEquipmentTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `equipment` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `equipment_id` varchar(50) NOT NULL COMMENT '设备ID',
            `equipment_name` varchar(100) NOT NULL COMMENT '设备名称',
            `equipment_type` varchar(20) NOT NULL COMMENT '设备类型：camera-相机，display-显示屏，charging-充电桩',
            `location` varchar(100) DEFAULT NULL COMMENT '位置',
            `ip_address` varchar(45) DEFAULT NULL COMMENT 'IP地址',
            `status` varchar(20) DEFAULT 'online' COMMENT '状态：online-在线，offline-离线，error-故障',
            `last_heartbeat` datetime DEFAULT NULL COMMENT '最后心跳时间',
            `version` varchar(20) DEFAULT NULL COMMENT '版本号',
            `install_date` date DEFAULT NULL COMMENT '安装日期',
            `config` text COMMENT '设备配置（JSON格式）',
            `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            UNIQUE KEY `equipment_id` (`equipment_id`),
            KEY `equipment_type` (`equipment_type`),
            KEY `status` (`status`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='设备表';
        ";
        
        Db::execute($sql);
    }
    
    // 创建维护记录表
    private static function createMaintenanceRecordsTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `maintenance_records` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `equipment_id` varchar(50) NOT NULL COMMENT '设备ID',
            `maintenance_type` varchar(50) NOT NULL COMMENT '维护类型',
            `description` text COMMENT '维护描述',
            `maintenance_date` date NOT NULL COMMENT '维护日期',
            `technician` varchar(50) DEFAULT NULL COMMENT '技术员',
            `status` varchar(20) DEFAULT '已完成' COMMENT '状态',
            `cost` decimal(10,2) DEFAULT 0.00 COMMENT '费用',
            `next_maintenance` date DEFAULT NULL COMMENT '下次维护时间',
            `create_time` datetime DEFAULT CURRENT_TIMESTAMP,
            `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            PRIMARY KEY (`id`),
            KEY `equipment_id` (`equipment_id`),
            KEY `maintenance_date` (`maintenance_date`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='维护记录表';
        ";
        
        Db::execute($sql);
    }
    
    // 创建进出场记录表
    public static function createParkingRecordsTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `parking_records` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `plate_number` varchar(20) NOT NULL COMMENT '车牌号',
            `plate_color` tinyint(1) DEFAULT 1 COMMENT '车牌颜色：1蓝牌 2黄牌 5绿牌',
            `record_type` tinyint(1) NOT NULL COMMENT '记录类型：1进场 2出场',
            `channel_id` varchar(50) DEFAULT '' COMMENT '通道ID',
            `record_time` datetime NOT NULL COMMENT '记录时间',
            `image_url` varchar(500) DEFAULT '' COMMENT '抓拍图片URL',
            `confidence` decimal(5,2) DEFAULT 0.00 COMMENT '识别置信度',
            `create_time` datetime NOT NULL COMMENT '创建时间',
            PRIMARY KEY (`id`),
            KEY `idx_plate_number` (`plate_number`),
            KEY `idx_record_time` (`record_time`),
            KEY `idx_channel_id` (`channel_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='进出场记录表';
        ";
        
        Db::execute($sql);
        return true;
    }
    
    // 创建续费记录表
    public static function createRenewalRecordsTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `renewal_records` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `plate_number` varchar(20) NOT NULL COMMENT '车牌号',
            `plate_color` tinyint(1) DEFAULT 1 COMMENT '车牌颜色',
            `renewal_amount` decimal(10,2) NOT NULL COMMENT '续费金额',
            `renewal_time` datetime NOT NULL COMMENT '续费时间',
            `renewal_months` int(3) DEFAULT 1 COMMENT '续费月数',
            `old_expire_time` datetime DEFAULT NULL COMMENT '原到期时间',
            `new_expire_time` datetime DEFAULT NULL COMMENT '新到期时间',
            `create_time` datetime NOT NULL COMMENT '创建时间',
            PRIMARY KEY (`id`),
            KEY `idx_plate_number` (`plate_number`),
            KEY `idx_renewal_time` (`renewal_time`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='续费记录表';
        ";
        
        Db::execute($sql);
        return true;
    }
    
    // 创建API调用日志表
    public static function createApiLogsTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `api_logs` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `api_name` varchar(100) NOT NULL COMMENT 'API名称',
            `request_url` varchar(500) NOT NULL COMMENT '请求URL',
            `request_method` varchar(10) DEFAULT 'POST' COMMENT '请求方法',
            `request_data` text COMMENT '请求数据',
            `response_data` text COMMENT '响应数据',
            `response_code` int(3) DEFAULT 0 COMMENT '响应状态码',
            `response_time` int(6) DEFAULT 0 COMMENT '响应时间(ms)',
            `status` tinyint(1) DEFAULT 0 COMMENT '调用状态：0失败 1成功',
            `error_message` text COMMENT '错误信息',
            `operator_id` int(11) DEFAULT 0 COMMENT '操作人ID',
            `create_time` datetime NOT NULL COMMENT '创建时间',
            PRIMARY KEY (`id`),
            KEY `idx_api_name` (`api_name`),
            KEY `idx_create_time` (`create_time`),
            KEY `idx_status` (`status`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='API调用日志表';
        ";
        
        Db::execute($sql);
        return true;
    }
    
    // 创建操作日志表
    public static function createOperationLogsTable()
    {
        $sql = "
        CREATE TABLE IF NOT EXISTS `operation_logs` (
            `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '日志ID',
            `operator` varchar(50) NOT NULL COMMENT '操作人',
            `operation` varchar(100) NOT NULL COMMENT '操作类型',
            `target_type` varchar(50) DEFAULT NULL COMMENT '操作对象类型',
            `target_id` varchar(50) DEFAULT NULL COMMENT '操作对象ID',
            `content` text COMMENT '操作内容',
            `ip_address` varchar(50) DEFAULT NULL COMMENT 'IP地址',
            `user_agent` varchar(255) DEFAULT NULL COMMENT '用户代理',
            `status` tinyint(1) DEFAULT 1 COMMENT '操作状态：1成功，0失败',
            `created_at` timestamp DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
            PRIMARY KEY (`id`),
            KEY `operator` (`operator`),
            KEY `operation` (`operation`),
            KEY `created_at` (`created_at`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='操作日志表';
        ";
        
        Db::execute($sql);
        return true;
    }
    
    // 更新通道表结构
    public static function updateChannelsTable()
    {
        // 检查是否需要添加新字段
        $columns = Db::query("SHOW COLUMNS FROM `channels`");
        $existingColumns = array_column($columns, 'Field');
        
        if (!in_array('gate_status', $existingColumns)) {
            $sql = "ALTER TABLE `channels` ADD COLUMN `gate_status` tinyint(1) DEFAULT 0 COMMENT '道闸状态：0关闭 1开启'";
            Db::execute($sql);
        }
        
        if (!in_array('device_id', $existingColumns)) {
            $sql = "ALTER TABLE `channels` ADD COLUMN `device_id` varchar(50) DEFAULT '' COMMENT '设备ID'";
            Db::execute($sql);
        }
        
        return true;
    }
    
    // 更新设备表结构
    public static function updateEquipmentTable()
    {
        // 检查是否需要添加新字段
        $columns = Db::query("SHOW COLUMNS FROM `equipment`");
        $existingColumns = array_column($columns, 'Field');
        
        if (!in_array('device_id', $existingColumns)) {
            $sql = "ALTER TABLE `equipment` ADD COLUMN `device_id` varchar(50) DEFAULT '' COMMENT '设备ID'";
            Db::execute($sql);
        }
        
        if (!in_array('last_heartbeat', $existingColumns)) {
            $sql = "ALTER TABLE `equipment` ADD COLUMN `last_heartbeat` datetime DEFAULT NULL COMMENT '最后心跳时间'";
            Db::execute($sql);
        }
        
        return true;
    }
    
    // 插入示例数据
    public static function insertSampleData()
    {
        try {
            // 插入车位示例数据
            self::insertSampleSpaces();
            
            // 插入通道示例数据
            self::insertSampleChannels();
            
            // 插入车辆示例数据
            self::insertSampleVehicles();
            
            // 插入设备示例数据
            self::insertSampleEquipment();
            
            return ['code' => 200, 'msg' => '示例数据插入成功'];
        } catch (\Exception $e) {
            return ['code' => 500, 'msg' => '示例数据插入失败：' . $e->getMessage()];
        }
    }
    
    // 插入车位示例数据
    private static function insertSampleSpaces()
    {
        $count = Db::table('parking_spaces')->count();
        if ($count > 0) return;
        
        $spaces = [];
        for ($i = 1; $i <= 500; $i++) {
            $area = chr(65 + ($i - 1) % 5); // A-E
            $number = str_pad(($i - 1) % 100 + 1, 3, '0', STR_PAD_LEFT);
            $floor = 'B' . (($i - 1) % 3 + 1);
            
            $spaces[] = [
                'space_no' => $area . '-' . $number,
                'space_type' => rand(1, 3),
                'status' => rand(1, 4),
                'floor' => $floor,
                'area' => $area,
                'create_time' => date('Y-m-d H:i:s')
            ];
        }
        
        Db::table('parking_spaces')->insertAll($spaces);
    }
    
    // 插入通道示例数据
    private static function insertSampleChannels()
    {
        $count = Db::table('channels')->count();
        if ($count > 0) return;
        
        $channels = [
            ['channel_name' => '入口1号通道', 'channel_type' => 1, 'camera_ip' => '192.168.1.101', 'location' => '北门入口'],
            ['channel_name' => '入口2号通道', 'channel_type' => 1, 'camera_ip' => '192.168.1.102', 'location' => '南门入口'],
            ['channel_name' => '入口3号通道', 'channel_type' => 1, 'camera_ip' => '192.168.1.103', 'location' => '东门入口'],
            ['channel_name' => '出口1号通道', 'channel_type' => 2, 'camera_ip' => '192.168.1.201', 'location' => '北门出口'],
            ['channel_name' => '出口2号通道', 'channel_type' => 2, 'camera_ip' => '192.168.1.202', 'location' => '南门出口'],
            ['channel_name' => '出口3号通道', 'channel_type' => 2, 'camera_ip' => '192.168.1.203', 'location' => '东门出口'],
        ];
        
        foreach ($channels as &$channel) {
            $channel['status'] = rand(1, 3);
            $channel['create_time'] = date('Y-m-d H:i:s');
        }
        
        Db::table('channels')->insertAll($channels);
    }
    
    // 插入车辆示例数据
    private static function insertSampleVehicles()
    {
        $count = Db::table('vehicles')->count();
        if ($count > 0) return;
        
        $vehicles = [];
        $cities = ['粤B', '粤A', '京A', '沪A', '津A'];
        $names = ['张三', '李四', '王五', '赵六', '钱七', '孙八'];
        
        for ($i = 1; $i <= 100; $i++) {
            $vehicles[] = [
                'plate_number' => $cities[rand(0, 4)] . rand(10000, 99999),
                'car_type' => rand(1, 3),
                'owner_name' => $names[rand(0, 5)],
                'phone' => '138' . rand(10000000, 99999999),
                'space_number' => chr(65 + rand(0, 4)) . '-' . str_pad(rand(1, 100), 3, '0', STR_PAD_LEFT),
                'expire_date' => date('Y-m-d H:i:s', time() + rand(86400, 31536000)),
                'balance' => rand(100, 1000),
                'status' => rand(1, 4),
                'create_time' => date('Y-m-d H:i:s')
            ];
        }
        
        Db::table('vehicles')->insertAll($vehicles);
    }
    
    // 插入设备示例数据
    private static function insertSampleEquipment()
    {
        $count = Db::table('equipment')->count();
        if ($count > 0) return;
        
        $equipment = [];
        
        // 相机设备
        for ($i = 1; $i <= 6; $i++) {
            $equipment[] = [
                'equipment_id' => 'CAM_' . str_pad($i, 3, '0', STR_PAD_LEFT),
                'equipment_name' => '相机' . $i . '号',
                'equipment_type' => 'camera',
                'location' => $i <= 3 ? '入口' . $i : '出口' . ($i - 3),
                'ip_address' => '192.168.1.' . (100 + $i),
                'status' => ['online', 'offline', 'error'][rand(0, 2)],
                'last_heartbeat' => date('Y-m-d H:i:s', time() - rand(0, 3600)),
                'version' => 'V1.0.' . rand(1, 9),
                'install_date' => date('Y-m-d', time() - rand(86400, 365 * 86400)),
                'create_time' => date('Y-m-d H:i:s')
            ];
        }
        
        // LED显示屏
        for ($i = 1; $i <= 4; $i++) {
            $equipment[] = [
                'equipment_id' => 'LED_' . str_pad($i, 3, '0', STR_PAD_LEFT),
                'equipment_name' => 'LED显示屏' . $i,
                'equipment_type' => 'display',
                'location' => $i <= 2 ? '入口' . $i : '出口' . ($i - 2),
                'ip_address' => '192.168.1.' . (120 + $i),
                'status' => ['online', 'offline', 'error'][rand(0, 2)],
                'last_heartbeat' => date('Y-m-d H:i:s', time() - rand(0, 3600)),
                'install_date' => date('Y-m-d', time() - rand(86400, 365 * 86400)),
                'create_time' => date('Y-m-d H:i:s')
            ];
        }
        
        // 充电桩
        for ($i = 1; $i <= 8; $i++) {
            $equipment[] = [
                'equipment_id' => 'CHG_' . str_pad($i, 3, '0', STR_PAD_LEFT),
                'equipment_name' => '充电桩' . $i . '号',
                'equipment_type' => 'charging',
                'location' => '地下' . (rand(1, 2)) . '层',
                'status' => ['online', 'offline', 'error'][rand(0, 2)],
                'last_heartbeat' => date('Y-m-d H:i:s', time() - rand(0, 3600)),
                'install_date' => date('Y-m-d', time() - rand(86400, 365 * 86400)),
                'create_time' => date('Y-m-d H:i:s')
            ];
        }
        
        Db::table('equipment')->insertAll($equipment);
    }
} 